<?php
/**
 * Created by PhpStorm.
 * User: silenceper
 * Date: 2017/1/9
 * Time: 下午6:12
 */

namespace common\services\common;


use common\entities\ConfigEntity;
use common\entities\ContractEntity;
use common\entities\myhtsq\ContractManageEntity;
use common\models\myhtsq\ContractManageModel;
use common\repositories\common\MyscrmContractProjectRepository;
use common\repositories\myhtsq\ContractManageRepository;
use common\repositories\myhtsq\ErpBusinessUnitRepository;
use common\services\BaseService;
use common\support\ExcelManage;

class MyscrmContractManageService extends BaseService
{
    protected $_contractManageRepository;

    public function __construct(ContractManageRepository $contractManageRepository, array $config = [])
    {
        $this->_contractManageRepository = $contractManageRepository;
        parent::__construct($config);
    }

    /**
     * 根据contract_code取数据
     * @param $code
     * @return array|null|ContractManageEntity
     */
    public function getContractManageByCode($code)
    {
        return $this->_contractManageRepository->getContractManageByCode($code);
    }
    /**
     * 根据contract_id取数据
     * @param $code
     * @return array|null|ContractManageEntity
     */
    public function getContractByContractIdOrErpContractId($contractId)
    {
        return $this->_contractManageRepository->getContractByContractIdOrErpContractId($contractId);
    }
    /**
     * 根据contract_id取数据
     * @param $code
     * @return array|null|ContractManageEntity
     */
    public function getContractBySignNumber($signNumber)
    {
        return $this->_contractManageRepository->getContractBySignNumber($signNumber);
    }
    /**
     * @param $buguid
     * @return string
     */
    public function getBunameByBuguid($buguid)
    {
        return ErpBusinessUnitRepository::getBunameByBuguid($buguid);
    }

    /**
     * 导入还款
     * @param $filePath
     * @return bool
     */
    public function importRepayment($filePath)
    {
        $data = ExcelManage::importDataByFilePath($filePath, 1);
        $i = 0;
        foreach ($data as $key => $row) {
            $i++;
            if ($i == 1) {
                //第一行为标题
                if (array_splice($row, 0, 4) != ["合同编号", "返款时间", "返款类型", "是否返款"]) {
                    return self::setAndReturn(-1, '导入模板不匹配，请重新选择模板');
                }
                //去除标题
                unset($data[$key]);
                continue;
            }
            //去除空行
            if (array_slice($row, 0, 4) == ["", "", "", ""]) {
                unset($data[$key]);
                continue;
            }
            //每行记录都必填,不允许为空,否则报错
            foreach ($row as $k => $val) {
                if (empty(trim($val))) {
                    return self::setAndReturn("-1", '字段不能为空');
                }
                $row[$k] = trim($val);
            }

            //返款日期 转为unix timestamp
            $date = \PHPExcel_Shared_Date::ExcelToPHP($row[1]);
            if (empty($date)) {
                return self::setAndReturn("-1", '返款日期不能为空');
            } else {
                $row[1] = date("Y-m-d",$date);
            }

            //返款类型
            $row[2] = $this->getRepaymentType($row[2]);
            if (false === $row[3]) {
                return self::setAndReturn("-1", '不能识别的返款类型' . $row[2]);
            }

            //是否返款
            $row[3] = $this->getRepaymentSure($row[3]);
            if (false === $row[3]) {
                return self::setAndReturn("-1", '不能识别的返款状态' . $row[3]);
            }

            $data[$key] = $row;
        }
        if (count($data) == 0) {
            return self::setAndReturn("-1", '请录入数据');
        }
        $transaction = ContractEntity::getDb()->beginTransaction();
        try {
            //开始导入
            foreach ($data as $row) {
                //根据合同号取
                $manageData = $this->_contractManageRepository->getContractManageByCode($row[0]);
                if (empty($manageData)) {
                    throw new \Exception('合同号不存在:' . $row[0]);
                }
                $manageData->repayment_time = $row[1];
                $manageData->repayment_type = $row[2];
                $manageData->balance_status = $row[3];
                if (false === $manageData->save(false)) {
                    throw new \Exception('保存失败');
                }
            }
            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return $this->setAndReturn(-1, $e->getMessage());
        }
        return true;
    }

    /**
     * 获取返款类型
     * @param $text
     * @return bool
     */
    private function getRepaymentType($text)
    {
        $arr = [
            '暂无' => 0,
            '现金' => 1,
            '转预收' => 2
        ];
        return isset($arr[$text]) ? $arr[$text] : false;
    }

    /**
     * 获取返款状态
     * @param $text
     * @return bool
     */
    private function getRepaymentSure($text)
    {
        $arr = [
            '未返款' => 0,
            '已返款' => 1,
        ];
        return isset($arr[$text]) ? $arr[$text] : false;
    }

    public function getContractsByCode(array $codes)
    {
        return $this->_contractManageRepository->getContractsByCode($codes);
    }
}